import './main.scss'

import {
  ref,
  reactive,
  watch,
  defineComponent,
  nextTick
} from 'vue'
import { ElMessage } from 'element-plus'

import {
  createComponentName,
  ComponentInstance,
  useExpose
} from '../utils'

import { getContactList } from '@/api/employe/riskmonitoring/messagearchiving'

import ZwDialog from '../dialog/Dialog'
import ZwSearchForm from '../search-form/SearchForm'
import ZwTable from '../table/Table'

import ImageMale from '@/assets/chatDetails/male.png'
import ImageFemale from '@/assets/chatDetails/female.png'

const [name, bem] = createComponentName('customer-popup')

export default defineComponent({
  name,

  props: {
    show: { // 显示弹框
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: true
    },
    defaultSelectRows: {
      type: Array,
      default: () => ([])
    }
  },

  emit: [
    'submit'
  ],

  setup(props, { emit }) {
    const tableRef = ref<null | ComponentInstance>(null)

    const defaultParams = {
      page_size: 10
    }

    const state = reactive({
      searchParams: defaultParams,
      selectRows: []
    })

    const searchOption = [
      {
        label: '客户姓名',
        name: 'name',
        value: '',
        type: 'input',
        placeholder: '请输入客户姓名进行搜索'
      },
      {
        label: '客户手机',
        name: 'mobile',
        value: '',
        type: 'input',
        placeholder: '请输入手机号进行搜索'
      },
      {
        label: '归属员工',
        name: 'work_user_ids',
        value: [],
        type: 'select',
        placeholder: '请选择员工',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        formatOption: (v: any) => ({
          label: v.name,
          value: v.id
        })
      }
    ]
  
    const search = (v: any) => {
      state.searchParams = v
      state.selectRows = []
      tableRef.value?.getTable()?.clearSelection()
    }

    const reset = () => {
      state.searchParams = defaultParams
    }

    const tableOption = [
      {
        type: 'selection',
        width: 55,
        fixed: 'left'
      },
      {
        prop: 'words_name',
        label: '客户姓名',
        render({ row }: any) {
          const styles = {
            width: '2.25rem',
            height: '2.25rem',
            verticalAlign: 'middle',
            marginRight: '0.625rem'
          }

          return (
            <>
              <img
                src={ row.avatar }
                style={ styles }
              />
              <span>{ row.name }</span>
              <img
                class={ bem('sex-img') }
                src={ row.sex === 1 ? ImageMale : ImageFemale }
              />
            </>
          )
        }
      },
      {
        prop: 'staff_touch_nums',
        label: '归属员工',
        render({ row }: any) {
          return (
            <>
              <span>{ row.assign_employees }</span>-<span>{ row.department_list[0] }</span>
            </>
          )
        }
      },
      {
        prop: 'created_at',
        label: '添加时间',
      }
    ]

    const onSelectionChange = (selection: any) => {
      if (props.multiple) {
        state.selectRows = selection
      } else {
        const tableListRef = tableRef.value?.getTable()
        state.selectRows = (selection.length && [selection[selection.length - 1]]) || []
        selection.forEach((row: any, rowIndex: number) => {
          if (rowIndex !== selection.length - 1) {
            tableListRef.toggleRowSelection(row, false)
          }
        })
      }
    }

    const onSelectAll = (selection: any) => {
      state.selectRows = selection
    }

    const onUpdateData = (list: any) => {
      nextTick(() => {
        const tableListRef = tableRef.value?.getTable()
        props.defaultSelectRows.forEach((row: any) => {
          const item = list.find((item: any) => row.id === item.id)
          tableListRef.toggleRowSelection(item, true)
        })
      })
    }

    // 关闭
    const onClose = () => {
      emit('update:show', false)
      reset()
    }

    // 取消选择
    const onCancel = () => {
      onClose()
    }

    // 保存选择
    const onSubmit = () => {
      state.selectRows = state.selectRows.filter(item => item)
      if (!state.selectRows.length) return ElMessage.error('请选择客户')
      onCancel()
      emit('submit', state.selectRows)
    }

    useExpose({})

    return () => {
      return (
        <ZwDialog
          show={ props.show }
          title="选择客户"
          width="69.25rem"
          onClose={ onClose }
          onCancel={ onCancel }
          onConfirm={ onSubmit }
        >
          <ZwSearchForm
            rowNum="3"
            option={ searchOption }
            onSearch={ search }
            onReset={ reset }
          />
          <ZwTable
            ref={ tableRef }
            class={ `${ bem('table') } ${ props.multiple ? '' : bem('table-radio') }` }
            option={ tableOption }
            fetchParams={ state.searchParams }
            fetchApi={ getContactList }
            pageSizes={ [10, 20, 50, 100] }
            onSelectionChange={ onSelectionChange }
            onSelectAll={ onSelectAll }
            onUpdateData={ onUpdateData }
          />
        </ZwDialog>
      )
    }
  }
})
